package main


import (
	"log"
	"time"
	"os"
	"os/exec"
	"context"
    "path/filepath"
	"github.com/gin-gonic/gin"
	"errors"
	"strconv"
	"net/http"
	"mygo/mystruct"
	"mygo/mymongo"
	"mygo/myws"
	"mygo/mylog"
	"mygo/mroute"
	"mygo/mauth"
	"mygo/global"
	"fmt"
	_ "net/http/pprof"
)

func init() {
	global.Init()
}

func main() {
	go func() {
        log.Println(http.ListenAndServe("0.0.0.0:6060", nil)) // 启动 pprof 服务
    }()
	if mymongo.MyMonDB.ApiCur.Collection == nil {
		mylog.ErrLog(fmt.Sprintf("数据库链接失败链接空对像"), global.Mtoken.Log_Path)
		panic(errors.New("数据库链接失败")) 
	}
	quit := make(chan int64)
	go mymongo.NewTickerFor(&global.Mtoken)
	go myws.NewTickerFor()

	r := gin.Default()
	r.Use(Authorize())

	r.Static("/js", filepath.Join(global.Mtoken.Web_Path, "js"))
	r.Static("/css", filepath.Join(global.Mtoken.Web_Path, "css"))
	r.Static("/images", filepath.Join(global.Mtoken.Web_Path, "images"))
	r.Static("/file", filepath.Join(global.Mtoken.File_Path))
	
	r.GET("/", func(c *gin.Context) {
		c.File(filepath.Join(global.Mtoken.Web_Path, "login.html"))
	})
	r.GET("/data", func(c *gin.Context) {
		c.File(filepath.Join(global.Mtoken.Web_Path, "index.html"))
	})
	r.GET("/api", func(c *gin.Context) {
		c.File(filepath.Join(global.Mtoken.Web_Path, "create.html"))
	})
	r.GET("/log", func(c *gin.Context) {
		c.File(filepath.Join(global.Mtoken.Web_Path, "log.html"))
	})

	r.GET("/word", func(c *gin.Context) {
		wordmodel := c.Query("model")
		if wordmodel == "0" {
			c.File(filepath.Join(global.Mtoken.Web_Path, "docs.html"))
		} else if (wordmodel == "1") {
			c.File(filepath.Join(global.Mtoken.Web_Path, "sheets.html"))
		}
	})

	r.GET("/code", func(c *gin.Context) {
		c.File(filepath.Join(global.Mtoken.Web_Path, "code.html"))
	})

	r.GET("/pack", func(c *gin.Context) {
		c.File(filepath.Join(global.Mtoken.Web_Path, "pack.html"))
	})

	r.POST("/api/getapi",  mauth.Auth_api(), mroute.MyApiGet)
	r.POST("/api/delapi",  mauth.Auth_api(), mroute.MyApiDel)
	r.POST("/api/addapi",  mauth.Auth_api(), mroute.MyApiAdd)
	r.POST("/api/setapi",  mauth.Auth_api(), mroute.MyApiSet)
	
	r.POST("/api/checks",  mroute.MyApiSeeAll)

	r.POST("/api/search_index", mauth.Auth_data(), mroute.MyApiIndexes)
	r.POST("/api/append",  		mauth.Auth_data(), mroute.MyAppend)
	r.POST("/api/update",  		mauth.Auth_data(), mroute.MyUpdate)
	r.POST("/api/delete",  		mauth.Auth_data(), mroute.MyDelete)
	r.POST("/api/wacth",   		mauth.Auth_data(), mroute.MyWacth)
	r.POST("/api/deleteall",  	mauth.Auth_data(), mroute.MyDeleteAll)
	r.POST("/api/appendall",  	mauth.Auth_data(), mroute.MyAppendAll)
	r.POST("/api/login",   	mroute.MyLogin)
	r.POST("/api/logout",  	mroute.MyLogout)

	r.GET("/api/checks",    mroute.Apicache)
	r.GET("/api/delete",    mauth.Auth_data(), mroute.MyDelete)
	r.GET("/api/wacth",     mauth.Auth_data(), mroute.MyWacth)
	r.GET("/api/fastwacth", mroute.MyFastWacth)
	r.GET("/api/wacthid",   mauth.Auth_data(), mroute.Mychake)
	r.GET("/api/upfield",   mauth.Auth_data(), mroute.MyUpField)
	r.GET("/api/export",    	mroute.MyExport)
	r.GET("/api/export_table",  mroute.MyExTable)
	r.GET("/api/download",  	mroute.Mydownload)
	r.HEAD("/api/download", 	mroute.FileHead)
	r.POST("/api/push",     	mroute.Myupfile)

	// 检查权限接口
	r.GET("/api/auth", 	mroute.MyAuth)

	// 在线文档接口
	r.GET("/api/word",  mauth.Auth_data(), mroute.MywordModel)
	r.POST("/api/word", mauth.Auth_data(), mroute.MywordModel)

	// 项目接口
	r.GET("/api/pack",  mauth.Auth_data(), mroute.Export_Pack)
	r.POST("/api/pack", mauth.Auth_data(), mroute.MypackModel)

	// 代码文本编辑接口
	r.GET("/api/code",  mauth.Auth_data(), mroute.MycodeModel)
	r.POST("/api/code", mauth.Auth_data(), mroute.MycodeModel)

	// 弹幕接口
	r.GET("/api/barrage/v3/",     mroute.MyBarrage_Api)
	r.POST("/api/barrage/v3/",    mroute.MyBarrage_Api)
	r.POST("/api/barrage/model/", mroute.MyBarrage_Model)

	//非代理接口
	r.POST("/api/user/register",  mroute.MyUserRegister)
	r.POST("/api/user/delete",    mroute.MyUserDelete)
	r.POST("/api/user/data",      mroute.MyUserData)
	
	r.GET("/api/ws",   	  mroute.MyWsApi)
	r.GET("/api/getip",   mroute.MyresIp)
	r.GET("/api/chcae",   mroute.MyChcaeModel)
	r.POST("/api/chcae",  mroute.MyChcaeModel)

	r.POST("/sysconfig",  mroute.MySysModel)
	r.POST("/api/sys",    mroute.MySysKey)
	r.GET("/api/sys",  	  func(c *gin.Context) {mroute.MySysApi(c, quit)})
	r.GET("/api/log",     mroute.MyLogApi)

	fmt.Println(fmt.Sprintf("\n初始秘钥: %s\n", global.Mtoken.Initcode))
	srv := &http.Server {
		Addr: ":" + strconv.FormatInt(global.Mtoken.Port, 10),
		Handler: r,
	}
	go func() {
		ipadr, err := mystruct.GetIpaddr()
		if err != nil {
			mylog.ErrLog(fmt.Sprintf("本地IP获取失败 %v", err), global.Mtoken.Log_Path)
		}
		fmt.Println(fmt.Sprintf("访问地址: http://%s:%s", ipadr, strconv.FormatInt(global.Mtoken.Port, 10)))
		if err := srv.ListenAndServe(); err != nil && err != http.ErrServerClosed {
			mylog.ErrLog(fmt.Sprintf("HTTP服务启动失败 %v", err), global.Mtoken.Log_Path)
			fmt.Printf("HTTP服务启动失败: %v\n", err)
		}
	}()
	select {
	case value := <-quit:
		switch value {
			case 1:
				ctx, _ := context.WithTimeout(context.Background(), 3*time.Second)
				err := srv.Shutdown(ctx)
				if err != nil {
					mylog.ErrLog(fmt.Sprintf("关闭服务失败 %v", err), global.Mtoken.Log_Path)
				}
			case 2:
				ctx, _ := context.WithTimeout(context.Background(), 3*time.Second)
				err := srv.Shutdown(ctx)
				if err == nil {
					cmd := exec.Command(os.Args[0], os.Args[1:]...)
					cmd.Stdout = os.Stdout
					cmd.Stderr = os.Stderr
					cmd.Start()
					os.Exit(0)
				}else{
					mylog.ErrLog(fmt.Sprintf("关闭服务失败 %v", err), global.Mtoken.Log_Path)
				}
		}
	}
}


/* =================================================================================
   跨域处理
*/
func Authorize() gin.HandlerFunc {
  return func(c *gin.Context) {
        method := c.Request.Method
        origin := c.Request.Header.Get("Origin") //请求头部
        if origin != "" {
            //接收客户端发送的origin （重要！）
            c.Writer.Header().Set("Access-Control-Allow-Origin", origin) 
            //服务器支持的所有跨域请求的方法
            c.Header("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, DELETE, UPDATE") 
            //允许跨域设置可以返回其他子段，可以自定义字段
            c.Header("Access-Control-Allow-Headers", "Authorization, Content-Length, X-CSRF-Token, Token,session")
            // 允许浏览器（客户端）可以解析的头部 （重要）
            c.Header("Access-Control-Expose-Headers", "Content-Length, Access-Control-Allow-Origin, Access-Control-Allow-Headers") 
            //设置缓存时间
            c.Header("Access-Control-Max-Age", "172800") 
            //允许客户端传递校验信息比如 cookie (重要)
            c.Header("Access-Control-Allow-Credentials", "true")                                                                                                                                                                                                                          
        }

        //允许类型校验 
        if method == "OPTIONS" {
			c.Header("Access-Control-Allow-Origin", "*")
            c.Header("Access-Control-Allow-Headers", "Content-Type, AccessToken, X-CSRF-Token, Authorization, UserNameBoot") //自定义 Header
            c.Header("Access-Control-Allow-Methods", "POST, GET, OPTIONS")
            c.Header("Access-Control-Expose-Headers", "Content-Length, Access-Control-Allow-Origin, Access-Control-Allow-Headers, Content-Type")
            c.Header("Access-Control-Allow-Credentials", "true")
            c.AbortWithStatus(mystruct.StatusOK)
        }
        defer func() {
            if err := recover(); err != nil {
                log.Printf("Panic info is: %v", err)
            }
        }()
        c.Next()
    }
}
// =================================================================================
